let app = getApp();
let userLoginInfo = {};
userLoginInfo.openidInfo = function(key) {
  let userInfo = wx.getStorageSync('userInfo') || {};
  let isLogin = wx.getStorageSync('isLogin') || false;
  return new Promise((resolve, rejece) => {
    function login() {
      wx.login({
        success: (res) => {
          app.util.request({
            url: 'auth/session/openid',
            data: {
              code: res.code,
            },
            cachetime: 0,
            success: (session) => {
              userInfo.sessionid = session.data.data.sessionid;
              userInfo.openid = session.data.data.openid;
              wx.setStorageSync('userInfo', userInfo);
              key ? (isLogin ? resolve(false) : resolve(true)) : resolve(false);
            },
          });
        },
      });
    }
    if (userInfo && userInfo.sessionid) {
      wx.checkSession({
        success: function() {
          key ? (isLogin ? resolve(false) : resolve(true)) : resolve(false);
        },
        fail: function() {
          login();
        },
      });
    } else {
      login();
    }
  });
};
/**
 * 更新用户信息；
 */

userLoginInfo.updataUserInfo = function(res) {
  let userInfo = wx.getStorageSync('userInfo');
  let updataMessage = function(response) {
    let res = JSON.parse(response);
    let historyPage = wx.getStorageSync('history_page') || '';
    res.openid = userInfo.openid;
    res.sessionid = userInfo.sessionid;
    wx.setStorageSync('userInfo', res);
    wx.setStorageSync('isLogin', true);
    if (historyPage) {
      wx.navigateTo({
        url: historyPage,
      });
    }
  };
  if (res) {
    updataMessage(res);
  } else {
    wx.getUserInfo({
      success: function(res) {
        updataMessage(res);
      },
    });
  }

};

module.exports = userLoginInfo;